<?php

namespace App\Http\Controllers\DingTalk;

use App\Http\Controllers\Controller;
use App\Models\DingTalkApp;
use App\Models\DingTalkSetting;
use Auth;
use App\Models\DingTalkAppUrl;
use App\Models\DingTalkDept;
use App\Models\User as DingTalkUser;

class SettingController extends Controller
{
    //
    public function index()
    {
        $gdata = DingTalkSetting::firstOrCreate();

        if (post("?")) {
            $id = post("id");
            if ((int)$id > 0) {
                return DingTalkAppUrl::where("app_id", $id)->get();
            } else {
                $data = post('data');
                // $data['logenable'] = isset($data['logenable']) ? 1 : 0;
                $gdata->update(unsetNull($data));
                DingTalkApp::saveitems(json_decode(post('items'), true));
                return success("保存成功");
            }
        } else {
            $param = array_merge($gdata->toArray(), F());
            $param['items'] = DingTalkApp::get();
            return view('DingTalk.SettingController.index', $param);
        }
    }

    //同步部门和用户
    public function reloaddd($dept_id = 1)
    {
        $data = app("DT")->department->list($dept_id);
        begin();
        //dept_id  =1 表示，从头开始同步
        if ($dept_id == 1) {
            DingTalkDept::where('id', ">", "0")->delete();
            //不触发createting
            DingTalkDept::insert(['dept_id' => '1', 'name' => '全部', 'parent_id' => 0, 'creator_id' => user()->id]);
            $this->reloaduser(1);
        }
        if ($data['errmsg'] == 'ok') {
            foreach ($data['result'] as $v) {
                $v['creator_id'] = user()->id;
                $this->reloaddd($v['dept_id']);
                $this->reloaduser($v['dept_id']);
                //不触发createting
                DingTalkDept::insert($v);
            }
        }
        commit();
        return success("同步完成！");
    }

    //根据部门同步用户
    protected function reloaduser($dept_id, $next_cursor = 0)
    {
        $data = app("DT")->user->getUsers($dept_id, $next_cursor);

        if ($data['errmsg'] == 'ok') {
            foreach ($data['result']['list'] as $v) {
                $v['creator_id'] = user()->id;
                $v['dept_id'] = $dept_id;
                DingTalkUser::updateOrCreate(['userid' => $v['userid']], $v);
            }
            if ($data['result']['has_more'] == true)
                $this->reloaduser($dept_id, $v['next_cursor']);
        } else {
            throwError($data['errmsg']);
        }
    }
}
